# -*- coding: utf-8 -*-
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
# 文件：post_qdzj_pay
# 日期：2020-06-01
# 备注：个人通用进件接口（加密）、放款
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

import requests
from interfacetest.baseset.qdzjmsloan_api import API_QDZJ
from pycacho.cachobase.logger import Logger
from pycacho.cachobase.deal_json import dict_to_json
from pycacho.cachobase.deal_time import minus_date
from msydwork.md5_encrypt import md5_encrypt
from msydwork.data.mysql_qdzj import get_order
import copy



logger = Logger("post_qdzj_pay").get_log()

fu_url = 'http://test.coo.msxiaodai.com/msloan/api/'

headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36'

        }

cur_time = minus_date(0,'q')
cur_day = minus_date(0,'s')

def get_sign(json_data,channel):
    if channel == 'IJFQ':
        secret_key = 'rsA8KESJkQ2A1E7xrT3SerLsx9v6RQJA8sfUjFeSjuJ88LPMLFq69DuxgNouTT7k'
    else:
        secret_key = 'W6daxVulibXgMW9TZFu5W3YnmzBpcIxXj8Tz2rhb2ZSFDLgac9x56S9bijUYp3Lk'
    # json_data['serviceHeader'] 里面'channelCd', 'productCd'
    keys = ['channelCd', 'productCd']
    org_str = ''
    for word in keys:
        org_str = org_str + word + '=' + str(json_data['serviceHeader'][word]) + '&'
    # json_data['serviceBody']['request'] 里面参数
    parm = []
    data = json_data['serviceBody']['request']
    for key in data:
        parm.append(key)
    parm.sort()
    for k in parm:
        org_str = org_str + k + '=' + str(data[k]).replace(' ', '').replace('\'', '"') + '&'
    o_token = org_str + 'sign=' + secret_key
    return(md5_encrypt(o_token))


# 借款申请(进件)
def xjh_apply(channel,product,i,uniqueId):
    data_list = API_QDZJ['CISXjhA_apply']
    if channel == 'XJH':
        json_data = copy.deepcopy(data_list)
        print('=',json_data)
    else:
        json_data = None
        print('暂不支持该渠道进件',channel)
        exit()
    json_data['service']['serviceHeader']['channelCd'] = channel
    json_data['service']['serviceHeader']['productCd'] = product
    json_data['service']['serviceBody']['request']['uniqueId'] = uniqueId
    json_data['service']['serviceBody']['request']['sign'] = get_sign(json_data['service'],channel)
    #print(json_data['service'])
    dict_to_json(json_data)
    req1 = requests.post(fu_url,json=json_data,headers=headers)
    data = req1.text
    logger.info("薪计划进件接口响应信息：%s",data)

# 放款申请
def xjh_loan(channel,product,i,unique_id):
    uniqueId = "PAY" + channel + cur_time + '%04d' % (i)
    if channel == 'XJH':
        json_data = copy.deepcopy(API_QDZJ['CISXjhLoanAApply'])
    else:
        json_data = None
        print('暂不支持该渠道放款', channel)
        exit()
    json_data['service']['serviceHeader']['channelCd'] = channel
    json_data['service']['serviceHeader']['productCd'] = product
    json_data['service']['serviceBody']['request']['uniqueId'] = uniqueId
    json_data['service']['serviceBody']['request']['orderNo'] = get_order(unique_id)
    json_data['service']['serviceBody']['request']['sign'] = get_sign(json_data['service'],channel)
    dict_to_json(json_data)
    req1 = requests.post(fu_url,json=json_data,headers=headers)
    data = req1.text
    logger.info("借款协议签约接口响应信息：%s",data)


# （yyyy-MM-dd），为空时默认当天
def transfer_record():
    fu_url ='http://test.coo.msxiaodai.com/test/xjh/cron/sign?lastDate=2020-11-12'
    req1 = requests.get(fu_url,headers=headers)
    data = req1.text
    logger.info("签署债权转让书、债转通知书接口响应信息：%s",data)


def batch_apply():
    for i in range(108,109):
        print('第' + str(i) +'笔进件：')
        unique_id = "APP" + channel + cur_day + '%08d' % (i)
        xjh_apply(channel,product,i,unique_id)

def batch_contract():
    for i in range(108,109):
        print('第' + str(i) +'笔合同签署：')
        unique_id = "APP" + channel + cur_day + '%08d' % (i)
        xjh_loan(channel,product,i,unique_id)


if __name__ == '__main__':
    channel = 'XJH'           #
    product = 'XJH003'        #
    i = 2
    if i == 0:
        unique_id = "APP" + channel + cur_time + '%04d' % (i)
        xjh_apply(channel,product,1,unique_id)
    elif i == 1:
        xjh_loan(channel,product,1,'')
    elif i == 2:
        batch_apply()
        batch_contract()
    elif i == 3:
        batch_contract()
    else:
        transfer_record()

